<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 应用中心->应用管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-row :gutter="10">
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-input v-model="query.data.appName" placeholder="应用名称" class="handle-input"></el-input>
                    </el-col>
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-select v-model="query.data.appType" placeholder="应用类型" class="handle-select" clearable>
                            <el-option v-for="item in appTypeList"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value">
                                <span style="float: left">{{ item.label }}</span>
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-select v-model="query.data.status" placeholder="应用状态" class="handle-select" clearable>
                            <el-option v-for="item in appStatusList"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value">
                                <span style="float: left">{{ item.label }}</span>
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-select v-model="query.data.domain" placeholder="业务域" class="handle-select" clearable>
                            <el-option v-for="item in domainList"
                                       :label="item.label"
                                       :value="item.name">
                                <span style="float: left">{{ item.label }}</span>
                            </el-option>
                        </el-select>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="24" :sm="12" style="text-align: left">
                        <el-button type="primary" icon="el-icon-search" @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :xs="24" :sm="12" style="text-align: right">
                        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
                        <el-button type="primary" icon="el-icon-refresh" @click="resetQueryForm">重置</el-button>
                    </el-col>
                </el-row>
            </div>

            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="应用ID" width="80"></el-table-column>
                <el-table-column prop="appCode" label="应用编码" width="180"></el-table-column>
                <el-table-column prop="appName" label="应用名称"></el-table-column>
                <el-table-column prop="appType" label="应用类型"></el-table-column>
                <el-table-column prop="domain" label="所属域"></el-table-column>
                <el-table-column prop="status" label="状态"></el-table-column>
                <el-table-column prop="date" label="操作信息"></el-table-column>
                <el-table-column label="操作" width="130" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit"
                                   @click="handleEdit(scope.$index, scope.row)">
                            编辑
                        </el-button>
                        <el-button type="text" icon="el-icon-delete" class="red"
                                @click="handleDelete(scope.$index, scope.row)">
                            删除
                        </el-button>
                        <el-button type="text" icon="el-icon-mobile"
                                   @click="handleNodes(scope.row)">
                            实例
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageVo.pageNo"
                        :page-size="query.pageVo.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%" max-height="480px">
            <el-form ref="form" :model="formData" label-width="100px">
                <el-form-item label="应用ID" v-show="formData.id ? true:false">
                    <el-input v-model="formData.id" :disabled="formData.id ? 'disabled':false"></el-input>
                </el-form-item>
                <el-form-item label="应用编码">
                    <el-input v-model="formData.appCode" :disabled="formData.id ? 'disabled':false"></el-input>
                </el-form-item>
                <el-form-item label="应用名称">
                    <el-input v-model="formData.appName"></el-input>
                </el-form-item>
                <el-form-item label="应用类型">
                    <el-select v-model="formData.appType" placeholder="应用类型" class="handle-select" clearable>
                        <el-option v-for="item in appTypeList"
                                   :label="item.label"
                                   :value="item.value">
                            <span style="float: left">{{ item.label }}</span>
                            <span style="float: right">{{ item.value }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属域">
                    <el-select v-model="formData.domain" class="handle-select">
                        <el-option v-for="item in domainList"
                                   :label="item.label"
                                   :value="item.name">
                            <span style="float: left">{{ item.label }}</span>
                            <span style="float: right">{{ item.name }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="应用状态">
                    <el-radio-group v-model="formData.status">
                        <el-radio-button v-for="item in appStatusList" :label="item.value">
                            {{ item.label }}
                        </el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="formData.remark"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="应用实例管理" :visible.sync="appNodeVisible" width="75%" :lock-scroll="false">
            <div id="zTreeMenu" style="top: 215px; left: 122px; visibility: hidden;">
                <ul>
                    <li id="m_add" @click="addAppNode">新增节点</li>
                    <li id="m_del" @click="delAppNode">删除节点</li>
                </ul>
            </div>
            <el-container style="height: 480px; padding:5px; border: 1px solid #eee">
                <el-aside width="480px">
                    <el-row>
                            <el-input v-model="appNodeFilterParam" placeholder="请输入应用节点/地址">
                                <el-button type="primary" slot="append" icon="el-icon-search"
                                           @click="filterAppNode" plain>搜索</el-button>
                                <el-button type="primary" slot="append" icon="el-icon-circle-plus-outline"
                                           @click="addAppNode" plain>新增</el-button>
                            </el-input>
                    </el-row>
                    <el-row>
                        <div>
                            <ul id="zTreeDiv" class="ztree"></ul>
                        </div>
                    </el-row>
                </el-aside>
                <el-container>
                    <el-header style="height:40px;">
                        <el-button type="primary" @click="doSaveNode" style="margin-top:5px; float:right">保 存</el-button>
                    </el-header>
                    <el-main style="padding-top:10px;">
                        <el-form ref="form" :model="appNodeData" label-width="140px">
                            <el-form-item label="所属应用">
                                <el-select v-model="appNodeData.appCode" class="handle-select" disabled>
                                    <el-option v-for="item in appList"
                                               :label="item.appName"
                                               :value="item.appCode">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="实例名称">
                                <el-input v-model="appNodeData.nodeName"></el-input>
                            </el-form-item>
                            <el-form-item label="主机地址">
                                <el-input v-model="appNodeData.host"></el-input>
                            </el-form-item>
                            <el-form-item label="端口">
                                <el-input v-model="appNodeData.port"></el-input>
                            </el-form-item>
                            <el-form-item label="状态">
                                <el-radio-group v-model="appNodeData.status">
                                    <el-radio-button v-for="item in appStatusList" :label="item.value">
                                        {{ item.label }}
                                    </el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="备注">
                                <el-input type="textarea" v-model="appNodeData.remark"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-main>
                </el-container>
            </el-container>


        </el-dialog>
    </div>

</template>

<script>
    import { listAppByPage, saveApp, deleteApp, listAppNodes, getAppNode, saveAppNode, deleteAppNode} from '../../api/appic/appInfo';
    import { listDomain } from '../../api/appic/appDomain';
    import { fetchDictByIndex } from '../../api/resic/dictionary';
    import "@/components/plugins/ztree/jquery.ztree.all.js";
    import "@/components/plugins/ztree/jquery.ztree.exhide.js";
    import "@/components/plugins/ztree/metroStyle/metroStyle.css";
    import { OnionUtils } from '../../utils/onion-utils';

    export default {
        name: 'basetable',
        data() {
            return {
                query: {
                    data:{
                        appName: '',
                        appType: '',
                    },
                    pageVo:{
                        pageNo: 1,
                        pageSize: 10
                    }
                },
                tableData: [],
                multipleSelection: [],
                delList: [],
                editVisible: false,
                appNodeVisible: false,
                pageTotal: 0,
                formData: {},
                idx: -1,
                id: -1,
                domainList:[],
                appList:[],
                appStatusList:[],
                appTypeList:[],
                appNodeData:{},
                appNodeZTree:{},
                appNodeFilterParam:'',
                zTreeSetting:{
                    view: {
                        dblClickExpand: false
                    },
                    check: {
                        enable: true
                    },
                    callback: {
                        onRightClick: this.handleZTreeMenu,
                        onClick: this.loadAppNode
                    }
                }
            };
        },
        created() {
            this.initData();
            this.getData();
            this.loadAppNodeTree([]);
        },
        //方法区
        methods: {
            initData(){
                let domainQueryParam = {
                    data: {},
                    pageVo: {
                        pageNo: 1,
                        pageSize: 1000
                    }
                };
                listDomain(domainQueryParam).then(res => {
                    this.domainList = res.data;
                });
                fetchDictByIndex("onion.app.status,onion.app.type").then(res => {
                    this.appStatusList = res.data["onion.app.status"];
                    this.appTypeList = res.data["onion.app.type"];
                });
            },
            //重置查询参数
            resetQueryForm(){
                this.query.data = {};
            },
            //获取应用信息列表
            getData() {
                listAppByPage(this.query).then(res => {
                    this.tableData = res.data.rows;
                    this.pageTotal = res.data.total || 50;
                });
            },
            //触发查询按键
            handleQuery() {
                this.$set(this.query, 'pageIndex', 1);
                this.getData();
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                .then(() => {
                    deleteApp(this.tableData[index].id).then(result =>{
                        this.$message.success('删除成功');
                        this.tableData.splice(index, 1);
                    });
                })
                .catch(() => {
                    this.$alert("异常！")
                });
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            delAllSelection() {
                const length = this.multipleSelection.length;
                let str = '';
                this.delList = this.delList.concat(this.multipleSelection);
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].name + ' ';
                }
                this.$message.error(`删除了${str}`);
                this.multipleSelection = [];
            },
            // 新增操作
            handleAdd(){
                this.formData = {};
                this.editVisible = true;
            },
            // 编辑操作
            handleEdit(index, row) {
                this.idx = index;
                this.formData = row;
                this.editVisible = true;
            },
            // 保存编辑
            saveEdit() {
                saveApp(this.formData).then(result => {
                    this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                    this.$set(this.tableData, this.idx, result.data);
                    this.editVisible = false;
                });
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            },
            //应用实例节点处理
            handleNodes(row){
                listAppNodes(row.appCode).then(res => {
                    let nodeArray = [];
                    for(let i=0; i<res.data.length; i++){
                        let zNode = new Object();
                        zNode.id = res.data[i].id;
                        zNode.name = "["+res.data[i].nodeName + "]" + res.data[i].host;
                        nodeArray[i] = zNode;
                    }
                    this.loadAppNodeTree(nodeArray);
                });
                this.formData = row;
                this.appList[0]={"appCode":row.appCode, "appName":row.appName};
                this.appNodeData = {"appCode" : row.appCode};
                this.appNodeVisible = true;
            },
            //加载应用节点Tree
            loadAppNodeTree(listAppNodes){
                $.fn.zTree.init($("#zTreeDiv"), this.zTreeSetting, listAppNodes)
                          .expandAll(true);
                this.appNodeZTree = $.fn.zTree.getZTreeObj("zTreeDiv");
            },
            //处理ZTree菜单
            handleZTreeMenu(event, treeId, treeNode) {
                if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                    this.appNodeZTree.cancelSelectedNode();
                    this.showZTreeMenu("root", event.clientX, event.clientY);
                } else if (treeNode && !treeNode.noR) {
                    this.appNodeZTree.selectNode(treeNode);
                    this.showZTreeMenu("node", event.clientX, event.clientY);
                }
            },
            //显示ZTree右键菜单
            showZTreeMenu(type, x, y) {
                if (type=="root") {
                } else {
                    $("#zTreeMenu ul").show();
                    $("#m_add").show();
                    $("#m_del").show();
                    y += document.body.scrollTop;
                    x += document.body.scrollLeft;
                    $("#zTreeMenu").css({"top":y+"px", "left":x+"px", "visibility":"visible"});
                    $("body").bind("mousedown", this.onBodyMouseDown);
                }
            },
            //隐藏ZTree右键菜单
            hideZTreeMenu() {
                if ($("#zTreeMenu")){
                    $("#zTreeMenu").css({"visibility": "hidden"});
                }
                $("body").unbind("mousedown", this.onBodyMouseDown);
            },
            //鼠标键按下事件
            onBodyMouseDown(event){
                if (!(event.target.id == "zTreeMenu" || $(event.target).parents("#zTreeMenu").length>0)) {
                    $("#zTreeMenu").css({"visibility" : "hidden"});
                }
            },
            //保存应用节点实例
            doSaveNode(){
                saveAppNode(this.appNodeData).then(result => {
                    if(result.code == 0){
                        this.appNodeData = result.data;
                        this.$message.success("应用节点实例保存成功！");
                    }else{
                        this.$alert("保存失败:" + result.message);
                    }
                });
            },
            //检索过滤应用节点
            filterAppNode(){
                let treeNodes = this.appNodeZTree.getNodes();
                this.seekAndFilterAppNode(treeNodes, this.appNodeFilterParam);
            },
            seekAndFilterAppNode(treeNodes, filterParam){
                if(!treeNodes || treeNodes.length==0){
                    return;
                }
                for(let i=0; i<treeNodes.length; i++){
                    if(OnionUtils.isEmpty(filterParam) || treeNodes[i].name.indexOf(filterParam)>-1){
                        this.appNodeZTree.showNode(treeNodes[i]);
                    }else{
                        this.appNodeZTree.hideNode(treeNodes[i]);
                    }
                    if(treeNodes[i].children && treeNodes[i].children.length>0){
                        this.seekAndFilterAppNode(treeNodes.children, filterParam);
                    }
                }
            },
            //新增应用实例节点
            addAppNode(){
                this.appNodeData = {"appCode" : this.formData.appCode};
            },
            //删除应用节点【AppNode】
            delAppNode(){
                this.hideZTreeMenu();
                let selectedNodes = this.appNodeZTree.getSelectedNodes();
                if(selectedNodes && selectedNodes.length==1){
                    this.$confirm('确定要删除吗？', '提示', {
                        type: 'warning'
                    }).then(() => {
                        deleteAppNode(selectedNodes[0].id).then(result =>{
                            if(result.code != 0){
                                this.$alert("删除失败："+result.message);
                            }else{
                                this.appNodeZTree.removeNode(selectedNodes[0]);
                                this.$message.success('删除成功');
                            }
                        });
                    }).catch(() => {
                        this.$alert("系统处理异常！")
                    });
                }
            },
            //加载AppNode
            loadAppNode(){
                //this.appList[0]={"appCode":this.formData.appCode, "nodeName":this.formData.nodeName};
                let selectedNodes = this.appNodeZTree.getSelectedNodes();
                if(selectedNodes && selectedNodes.length==1){
                    getAppNode(selectedNodes[0].id).then(res =>{
                        this.appNodeData = res.data;
                    });
                }
            },
            //展开
            expandClick(node){
            },
            //右键
            contextmenuClick(node){
            }
        }
    };
</script>

<style>
    .handle-box {
        margin-bottom: 10px;
    }

    .handle-select {
        width: 100%;
    }

    .handle-input {
        width: 100%;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

    .el-dialog__body{
        padding: 15px;
    }

    ul.ztree {
        width: auto;
        height: 410px;
        overflow-y: auto;
    }

    div.zTreeDemoBackground{
        height: 300px;
    }

    div#zTreeMenu {
        z-index: 9999;
        position:fixed;
        visibility:hidden;
        top:0;
        background-color: #555;
        text-align: left;
        padding: 2px;
    }

    div#zTreeMenu ul li{
        margin: 1px 0;
        padding: 0 5px;
        cursor: pointer;
        list-style: none outside none;
        background-color: #DFDFDF;
    }

</style>